package com.heima.schedule.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.heima.common.redis.CacheService;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/24
 */
@Service
@Slf4j
@Transactional
public class TaskServiceImpl implements TaskService {
    @Autowired
    private CacheService cacheService;
    /**
     * 添加任务
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public Long addTask(Task task) {
        //添加任务到数据库中
        Boolean success = addTaskToDb(task);
        if (success) {
            //添加任务到redis
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     * @param taskId 任务id
     * @return 操作结果
     */
    @Override
    public Boolean cancelTask(Long taskId) {
        Boolean flag = false;
        //删除任务，更新日志
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
        if (ObjectUtil.isNotEmpty(task)) {
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 按照类型和优先级拉取任务
     * @param type     任务类型
     * @param priority 任务优先级
     * @return
     */
    @Override
    public Task poll(Integer type, Integer priority) {
        Task task = null;
        try {
            String key = type + "_" + priority;
            String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(taskJson)) {
                task = JSON.parseObject(taskJson, Task.class);
                //更新数据库信息
                updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            log.error("poll task exception");
            e.printStackTrace();
        }
        return task;
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
//        System.out.println(System.currentTimeMillis()/1000 + "执行定时任务。。。");
        //分布式锁解决分布式系统共享资源问题
        String token = cacheService.tryLock(
                ScheduleConstants.FUTURE_TASK_SUMC, ScheduleConstants.LOCK_EXPIRE);
        if (StringUtils.isNotBlank(token)){
            //log.info("定时任务 --> 未来数据定时刷新");
            //获取所有未来数据集合的key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*"); //future_*
            for (String futureKey : futureKeys) {   //future_250_250
                //获取改组key下当前需要消费的任务数据
                //按照key和分值查询符合条件的数据
                Set<String> tasks = cacheService.zRangeByScore(
                        futureKey, 0, System.currentTimeMillis());
                //同步数据
                if (CollUtil.isNotEmpty(tasks)) {
                    //获取当前数据的key  topic_ + type_priority
                    String topicKey = ScheduleConstants.TOPIC +
                            futureKey.split(ScheduleConstants.FUTURE)[1];
                    //将这些任务添加到消费者队列(list中)，同时从ZSet中删除
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    //log.info(futureKey + "下的当前需要执行的任务已刷新到" + topicKey);
                }
            }
        }
        //释放同步锁
        cacheService.delete("FUTURE_TASK_SUMC_lock");
    }

    /**
     * 数据库同步到redis
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct  //初始化 --> 微服务启动时执行
    public void reloadData() {
        //清理redis中的任务后再同步，防止重复执行
        clearCache();
        log.info("数据库数据同步到缓存 --> begin");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        //查看数据库中未来5分钟的所有任务
        List<Taskinfo> taskinfos = taskinfoMapper.queryFutureTime(
                TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                TaskTypeEnum.NEWS_SCAN_TIME.getPriority(), calendar.getTime());
        /*List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers
                .<Taskinfo>lambdaQuery()
                .lt(Taskinfo::getExecuteTime, calendar.getTime()));*/
        if (CollUtil.isNotEmpty(taskinfos)) {
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtil.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                //同步到缓存
                addTaskToCache(task);
            }
        }
        //log.info("数据库数据同步到缓存 --> end");
    }

    /**
     * 删除缓存中未来数据集合和当前消费者队列的所有key
     */
    private void clearCache() {
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*"); //future_*
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");   //topic_*
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }

    /**
     * 删除redis中的task
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        if (ObjectUtil.isEmpty(task)) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
        String key = task.getTaskType() + "_" + task.getPriority();
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //已过期 --> 删除所有过期任务
            cacheService.lRemove(
                    ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            //未过期 --> 删除指定任务
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除数据库任务，更新数据库任务日志状态
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(Long taskId, Integer status) {
        Task task = null;
        try {
            taskinfoMapper.deleteById(taskId);
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            task = new Task();
            BeanUtil.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            log.error("task cancel exception: taskId={}", taskId);
            e.printStackTrace();
        }
        return task;
    }

    /**
     * 把任务添加到redis
     * @param task
     */
    private void addTaskToCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        //获取五分钟之后的时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, ScheduleConstants.REFRESH_TIME);
        long nextScheduleTime = calendar.getTimeInMillis();
        //如果任务的执行时间小于等于当前时间，存入list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= nextScheduleTime) {
            //如果任务的执行时间大于当前时间 && 小于等于预设时间（未来5分钟） 存入zset中
            cacheService.zAdd(ScheduleConstants.FUTURE + key,
                    JSON.toJSONString(task),
                    task.getExecuteTime());
        }
    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    /**
     * 把任务添加到数据库
     * @param task
     * @return
     */
    private Boolean addTaskToDb(Task task) {
        Boolean flag = false;
        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtil.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            //设置taskid
            task.setTaskId(taskinfo.getTaskId());
            //保存任务日志
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtil.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(ScheduleConstants.VERSION_INIT);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
